<!-- JobEditView.vue -->
<template>
  <div id="app">
    <!-- 添加导航栏 -->
    <AppNavbar />

    <div class="job-edit-container">
      <h2>编辑职位信息</h2>
      <form @submit.prevent="submitForm" class="job-form">
        <div class="form-group">
          <label for="positionName">职位名称:</label>
          <input
            id="positionName"
            v-model="formData.positionName"
            type="text"
            required
            class="form-control"
          />
        </div>

        <div class="form-group">
          <label for="positionType">职位类型:</label>
          <select
            id="positionType"
            v-model="formData.positionType"
            required
            class="form-control"
          >
            <option value="full-time">全职</option>
            <option value="part-time">兼职</option>
            <option value="internship">实习</option>
          </select>
        </div>

        <div class="form-group salary-group">
          <label>薪资范围:</label>
          <div class="salary-inputs">
            <input
              v-model="salary.min"
              type="number"
              placeholder="最小值"
              required
              class="form-control"
            />
            <span>-</span>
            <input
              v-model="salary.max"
              type="number"
              placeholder="最大值"
              required
              class="form-control"
            />
            <select v-model="salary.unit" class="form-control">
              <option value="K">K</option>
              <option value="元">元</option>
            </select>
          </div>
        </div>

        <div class="form-group">
          <label for="department">部门:</label>
          <input
            id="department"
            v-model="formData.department"
            type="text"
            required
            class="form-control"
          />
        </div>

        <div class="form-group">
          <label for="province">省份:</label>
          <select
            id="province"
            v-model="formData.province"
            required
            class="form-control"
          >
            <option value="">请选择省份</option>
            <option value="北京市">北京市</option>
            <option value="上海市">上海市</option>
            <option value="天津市">天津市</option>
            <option value="重庆市">重庆市</option>
            <option value="河北省">河北省</option>
            <option value="山西省">山西省</option>
            <option value="辽宁省">辽宁省</option>
            <option value="吉林省">吉林省</option>
            <option value="黑龙江省">黑龙江省</option>
            <option value="江苏省">江苏省</option>
            <option value="浙江省">浙江省</option>
            <option value="安徽省">安徽省</option>
            <option value="福建省">福建省</option>
            <option value="江西省">江西省</option>
            <option value="山东省">山东省</option>
            <option value="河南省">河南省</option>
            <option value="湖北省">湖北省</option>
            <option value="湖南省">湖南省</option>
            <option value="广东省">广东省</option>
            <option value="海南省">海南省</option>
            <option value="四川省">四川省</option>
            <option value="贵州省">贵州省</option>
            <option value="云南省">云南省</option>
            <option value="陕西省">陕西省</option>
            <option value="甘肃省">甘肃省</option>
            <option value="青海省">青海省</option>
            <option value="台湾省">台湾省</option>
            <option value="内蒙古自治区">内蒙古自治区</option>
            <option value="广西壮族自治区">广西壮族自治区</option>
            <option value="西藏自治区">西藏自治区</option>
            <option value="宁夏回族自治区">宁夏回族自治区</option>
            <option value="新疆维吾尔自治区">新疆维吾尔自治区</option>
            <option value="香港特别行政区">香港特别行政区</option>
            <option value="澳门特别行政区">澳门特别行政区</option>
          </select>
        </div>

        <div class="form-group">
          <label for="ability">能力要求:</label>
          <textarea
            id="ability"
            v-model="formData.ability"
            required
            class="form-control"
          ></textarea>
        </div>

        <div class="form-group">
          <label for="jobDescription">职位描述:</label>
          <textarea
            id="jobDescription"
            v-model="formData.jobDescription"
            required
            class="form-control"
          ></textarea>
        </div>

        <div class="form-group">
          <label>技能标签:</label>
          <div class="tag-selection">
            <div class="tag-group">
              <select v-model="selectedCategory" @change="clearSubCategory" class="form-control">
                <option value="">选择分类</option>
                <option v-for="(tags, category) in tagList" :key="category" :value="category">
                  {{ category }}
                </option>
              </select>
            </div>
            <div class="tag-group">
              <select
                v-model="selectedSubCategory"
                :disabled="!selectedCategory"
                class="form-control"
              >
                <option value="">选择子分类</option>
                <option
                  v-for="tag in tagList[selectedCategory]"
                  :key="tag"
                  :value="tag"
                >
                  {{ tag }}
                </option>
              </select>
            </div>
            <button
              type="button"
              @click="addTag"
              :disabled="!selectedSubCategory"
              class="add-tag-btn"
            >
              添加标签
            </button>
          </div>

          <div class="selected-tags">
            <span
              v-for="(tag, index) in formData.tagList"
              :key="index"
              class="tag"
            >
              {{ tag }}
              <button type="button" @click="removeTag(index)" class="remove-tag">×</button>
            </span>
          </div>
        </div>

        <div class="form-actions">
          <button type="submit" class="submit-btn">保存修改</button>
          <button type="button" @click="cancel" class="cancel-btn">取消</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import apiClient from '@/utils/api'
import AppNavbar from '@/components/AppNavbar.vue'

export default {
  name: 'JobEdit',
  components: {
    AppNavbar
  },
  setup () {
    const route = useRoute()
    const router = useRouter()

    const formData = reactive({
      positionId: null,
      employerId: null,
      positionName: '',
      positionType: 'full-time',
      department: '',
      province: '',
      ability: '',
      jobDescription: '',
      tagList: []
    })

    const salary = reactive({
      min: '',
      max: '',
      unit: 'K'
    })

    const tagList = ref({})
    const selectedCategory = ref('')
    const selectedSubCategory = ref('')

    // 获取职位详情
    const fetchJobDetail = async () => {
      try {
        const positionId = route.params.positionId
        const response = await apiClient.get(`/employer/jobDetail?positionId=${positionId}`)

        if (response.data.code === '200') {
          const data = response.data.data
          formData.positionId = data.positionId
          formData.employerId = data.employerId
          formData.positionName = data.positionName
          formData.positionType = data.positionType
          formData.department = data.department
          formData.province = data.province || ''
          formData.ability = data.ability
          formData.jobDescription = data.jobDescription
          formData.tagList = data.tagList || []

          // 解析薪资范围
          if (data.salaryRange) {
            const [min, maxWithUnit] = data.salaryRange.split('-')
            salary.min = min.replace(/\D/g, '')
            salary.max = maxWithUnit.replace(/\D/g, '')
            salary.unit = data.salaryRange.includes('K') ? 'K' : '元'
          }
        }
      } catch (error) {
        console.error('获取职位详情失败:', error)
      }
    }

    // 获取标签列表
    const fetchTagList = async () => {
      try {
        const response = await apiClient.get('/job/tagList')
        if (response.data.code === '200') {
          tagList.value = response.data.data
        }
      } catch (error) {
        console.error('获取标签列表失败:', error)
      }
    }

    // 添加标签
    const addTag = () => {
      if (selectedSubCategory.value && !formData.tagList.includes(selectedSubCategory.value)) {
        formData.tagList.push(selectedSubCategory.value)
        clearSubCategory()
      }
    }

    // 移除标签
    const removeTag = (index) => {
      formData.tagList.splice(index, 1)
    }

    // 清除子分类选择
    const clearSubCategory = () => {
      selectedSubCategory.value = ''
    }

    // 提交表单
    const submitForm = async () => {
      try {
        const submitData = {
          ...formData,
          salaryRange: `${salary.min}${salary.unit}-${salary.max}${salary.unit}`
        }

        const response = await apiClient.post('/employer/updateJobPosition', submitData)

        if (response.data.code === '200') {
          alert('职位信息更新成功')
          router.push('/employerJobList')
        } else {
          alert(`更新失败: ${response.data.msg}`)
        }
      } catch (error) {
        console.error('提交表单失败:', error)
        alert('提交失败，请重试')
      }
    }

    // 取消编辑
    const cancel = () => {
      router.push('/employerJobList')
    }

    onMounted(() => {
      fetchJobDetail()
      fetchTagList()
    })

    return {
      formData,
      salary,
      tagList,
      selectedCategory,
      selectedSubCategory,
      addTag,
      removeTag,
      clearSubCategory,
      submitForm,
      cancel
    }
  }
}
</script>

<style scoped>
#app {
  background: linear-gradient(to right, #e0f7fa, #ffffff);
  min-height: 100vh;
  padding: 20px;
}

.job-edit-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

h2 {
  color: #1890ff;
  text-align: center;
  margin-bottom: 30px;
}

.job-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 8px;
  font-weight: bold;
  color: #333;
}

.form-control {
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-control:focus {
  border-color: #1890ff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.salary-group label {
  margin-bottom: 8px;
}

.salary-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
}

.salary-inputs input,
.salary-inputs select {
  flex: 1;
}

.tag-selection {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-bottom: 15px;
}

.tag-group {
  flex: 1;
}

.add-tag-btn {
  padding: 10px 15px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.add-tag-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.add-tag-btn:hover:not(:disabled) {
  background-color: #40a9ff;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.tag {
  display: inline-flex;
  align-items: center;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  padding: 5px 10px;
  color: #1890ff;
}

.remove-tag {
  background: none;
  border: none;
  color: #ff4d4f;
  font-size: 16px;
  cursor: pointer;
  margin-left: 5px;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.submit-btn, .cancel-btn {
  padding: 10px 30px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn {
  background-color: #1890ff;
  color: white;
}

.submit-btn:hover {
  background-color: #40a9ff;
}

.cancel-btn {
  background-color: #fff;
  color: #1890ff;
  border: 1px solid #1890ff;
}

.cancel-btn:hover {
  background-color: #e6f7ff;
}

textarea.form-control {
  min-height: 100px;
  resize: vertical;
}
</style>
